package main;

import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.List;

import tools.UniprotJAPI;
import au.com.bytecode.opencsv.CSVReader;

public class UnpdateUniprotIDs {

	public List<String[]> UpdateCSV(String datasetString, int col) {
		try {
			CSVReader originalReader;
			originalReader = new CSVReader(new FileReader(datasetString), '\t');
			List<String[]> originalEntries = originalReader.readAll();
			originalEntries.remove(0);
			UniprotJAPI uniprotJAPI = new UniprotJAPI();
			int count = 0;
			for (String[] line : originalEntries) {
				String newValue = "";

				// Check if the accession is valid. Take appropriate action.
				// check if primary accession
				if (uniprotJAPI.checkIsPrimaryAccession(line[col])) {
					newValue = line[col];
				} else
				// secondary of deleted
				{
					// check if deleted
					String accession = "";
					if ((accession = uniprotJAPI
							.getPrimaryAccessionFromSecondary(line[col])) != null) {
						newValue = accession;
					} else {
						newValue = "deleted";
					}
				}
				line[col + 1] = newValue;
				System.out.println(newValue + "\t" + count++);

			}
			return originalEntries;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public void writeData(List<String[]> data, String outPAth) {
		try {
			// Create file
			FileWriter fstream = new FileWriter(outPAth);
			BufferedWriter out = new BufferedWriter(fstream);

			for (String[] line : data)
			{
				String newLine = "";
				for (String col : line)
				{
					newLine = newLine + "\t" + col;
				}
				out.write(newLine + "\n");
			}
			
			// Close the output stream
			out.close();
		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
	}

	public static void main(String[] args) {
		UnpdateUniprotIDs main = new UnpdateUniprotIDs();
		
		{
			List<String[]> allProteins = main
					.UpdateCSV(
							"/home/kevin/Desktop/Uniprot_Updater/jobs/tissue_index_data_Uniprot.csv",
							1);
			main.writeData(allProteins, "/home/kevin/Desktop/Uniprot_Updater/jobs/tissue_index_data_UniprotUPDATED.csv");
		}
	}
}
